
import React from 'react';
import { Redirect } from 'react-router-dom'
import {BaseUrl} from '../common/common'
import Version from '../version.js'
import { Require } from '../../axios.jsx';
import { Form, Icon, Input, Button, message, TimePicker, Select, Cascader, InputNumber } from 'antd';
const { Option } = Select;
class NormalLoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            login:true,
            email:null,
            password1:null,
            flags:false,
            showsign:false,
            spinlogin:false,
            loginFlag:false
        }
    }
    componentDidMount(){
        const login = this.LogIn;
        var i = 0;
        const showSign_1 = this.setSignShow;
        document.addEventListener("keydown",function(e){
            if(e.keyCode == 13){
                i++;
                if( i == 1){
                    login()
                }else{
                    showSign_1()
                }
            }
        })
        Require({
        	method: 'post',
        	url:"/login",
        	data:{
                "usernamne":"123",
                "password":"123"
            }
        })
        .then((result)=>{

        	if(result.code == 0){
        		console.log(result)
        	}
        	else if(result.code == 10){
        		
        	}
        })
        .catch((err)=>{
            console.log(err);
            alert(err);
        })
    }

    handleChangeEmail(event) {
        this.setState({email: event.target.value});
    }
    handleChangePassword(event1) {
        this.setState({password1: event1.target.value});
    }
    handleSubmit = (e) => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
            }
            this.LogIn();
        });
    }

    setLoginSpin =() =>{
        this.setState({
            spinlogin:false,
        })
    }

    setSignShow = () => {
        this.setState({
            showsign:true,
        });
    }

    //隐藏登陆注册组件
    hideSignModal = ()=>{
        this.props.SignFlag();
        this.props.setLoadTrue();
    }
    LogIn = () => {
       this.setState({
        loginFlag:true
       })
        const showSign = this.setSignShow;
        const setLoadTrue = this.setLoginSpin;
        const url =  BaseUrl + "/user/login";
        const options = {
            method: 'POST',
            mode:'cors',
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json',
            },
        };
        if(this.state.email == null || this.state.password1 == null ||this.state.password1 == "" || this.state.email == ""){
            // Modal.info({
            //     zIndex:1002,
            //     title: '提示信息',
            //     content:'账号或密码不能为空',
            //     onOk() {},
            // });
            return ;
        }else{
            Promise.race([fetch(url, {
                ...options, body: JSON.stringify({
                    "email":this.state.email,
                    "password":this.state.password1
                }),
            }), new Promise(function (resolve, reject) {
                setTimeout(() => reject(new Error('request timeout')), 30000);
            })]).then(response => response.json()).then(result =>{
                if(result.status === 0){
                    if(!window.localStorage){
                        alert("浏览器不支持sessionStorage");
                    }else{
                        window.localStorage.setItem("token",result["token"]);
                        window.localStorage.setItem("type",result["type"]);
                    }
                    window.localStorage.setItem("username",this.state.email);
                    setLoadTrue();
                    // Modal.info({
                    //     zIndex:1004,
                    //     title: '提示信息',
                    //     content: (<div>{result.msg}</div>),
                    //     onOk() { showSign();},
                    // });
                }else{
                    setLoadTrue();
                    // Modal.info({
                    //     title: '提示信息',
                    //     zIndex:1004,
                    //     content: ( <div>登陆失败 {result.msg}</div>),
                    //     onOk() {},
                    // });
                }
            }).catch(error => {
                setLoadTrue();
                // Modal.info({
                //     title: '提示信息',
                //     zIndex:1004,
                //     content: (<div>登陆超时</div>),
                //     onOk() {showSign() },
                // });
                console.info('  login error', error);
            });

        }
        this.setState({
            spinlogin:true,
        })
    }
    render() {
      const { getFieldDecorator } = this.props.form;
        return (
            <div style={{ height:"100%",width:"100%"}}>
            <div  className="login"  style={{ height:"100%", width:"100%",display:'flex',justifyContent:'center',alignItems:'center'}}>
                <img src={require('../../assets/bg.png')} style={{position:'fixed',top:0,width:'100%',height:'100%'}} alt="" />
                <div style={{zIndex:'99'}}>
                  <Form onSubmit={this.handleSubmit} className="login-form">
                    <h2 style={{textAlign:'center'}}>欢迎使用品识</h2>
                  <Form.Item>
                    {getFieldDecorator('UserName', {
                      rules: [{ required: true, message: '请输入您的账户!' }],
                    })(
                      <Input
                        prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        placeholder="UserName"
                      />,
                    )}
                  </Form.Item>
                  <Form.Item>
                    {getFieldDecorator('PassWord', {
                      rules: [{ required: true, message: '请输入您的密码!' }],
                    })(
                      <Input
                        prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
                        type="password"
                        placeholder="PassWord"
                      />,
                    )}
                  </Form.Item>
                  <Form.Item>
                    <Button type="primary" htmlType="submit" className="login-form-button">
                      登录
                    </Button>
                  </Form.Item>
                </Form>
                {
                  this.state.loginFlag == true?
                  <Redirect  to="/layout/test"></Redirect>
                  :""
                }
                </div>
            </div>
        </div>
            );
        }
    }
const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
export default WrappedNormalLoginForm
